package com.gjty.healthmgr.configuration;

import com.gjty.healthmgr.comm.MySessionListener;
import com.gjty.healthmgr.shiro.MyRealm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.SessionListener;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfiguration {

    @Bean
    public ShiroFilterFactoryBean createShiroFilterFactoryBean(SecurityManager securityManager) {

        ShiroFilterFactoryBean sff = new ShiroFilterFactoryBean();

        sff.setSecurityManager(securityManager);
        Map<String, String> filterChainDefinitionMap = new HashMap<>();

        sff.setLoginUrl("/login");

        sff.setUnauthorizedUrl("/403");

        sff.setFilterChainDefinitionMap(filterChainDefinitionMap);

        return sff;

    }


    @Bean
    public SecurityManager securityManager(MyRealm myRealm,SessionManager sessionManager) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//        MyRealm myRealm = new MyRealm();
        securityManager.setRealm(myRealm);
        securityManager.setSessionManager(sessionManager);
//        securityManager.setCacheManager(ehCacheManager());
        return securityManager;
    }

    @Bean
    public SessionManager sessionManager(MySessionListener mySessionListener) {
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        Collection<SessionListener> listeners = new ArrayList<SessionListener>();
        listeners.add(mySessionListener);
        sessionManager.setSessionListeners(listeners);
        return sessionManager;
    }
}
